package com.kai.mqtt.config;

import com.kai.mqtt.cache.AccessTokenCache;
import com.kai.mqtt.enums.ErrorCodeEnum;
import com.kai.mqtt.exception.BusinessException;
import com.kai.mqtt.util.LoginLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author weijk
 * @since 2024/7/2
 */
@Component
public class SecurityHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String accessToken = request.getHeader("Access-Token");
        if (!StringUtils.hasText(accessToken) || !AccessTokenCache.checkToken(accessToken)) {
            throw new BusinessException(ErrorCodeEnum.TOKEN_ERROR);
        }

        LoginLocalUtil.setToken(accessToken);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LoginLocalUtil.clear();
    }
}
